package com.example.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.dto.WechatReturnObjectDTO;
import com.example.entity.po.AuditRecord;
import com.example.entity.po.User;
import com.example.entity.vo.UserInfoVO;
import com.example.exception.ServiceException;
import com.example.mapper.AuditRecordMapper;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import com.example.utils.JwtUtil;
import com.example.utils.WechatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Zeran2023
 * @description 针对表【t_user】的数据库操作Service实现
 * @createDate 2024-12-24 14:40:18
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private AuditRecordMapper auditRecordMapper;
	@Autowired
	private WechatUtil wechatUtil;

	@Override
	public void updateUserById(User user) {
		// 验证字段是否为空
		if (ObjectUtil.isNull(user)) {
			throw new ServiceException("用户对象不能为空");
		}
		// 先使用wrapper查询是否存在该用户，然后更新用户
		User dataUser = userMapper.selectById(user.getUserId());
		if (ObjectUtil.isNull(dataUser)) {
			throw new ServiceException("用户不存在");
		}
		try {
			userMapper.updateById(user);
		} catch (Exception e) {
			throw new ServiceException("数据库更新失败");
		}
	}

	@Override
	public UserInfoVO getUserInfo(String token) {
		String userId = JwtUtil.parseTokenId(token);
		User user = userMapper.selectById(userId);
		if (user == null) {
			throw new ServiceException("用户不存在");
		}

		UserInfoVO userInfo = UserInfoVO.builder()
				.username(user.getUsername())
				.nickname(user.getNickname())
				.userImg(user.getAvatar())
				.build();

		// 获取待审核数量、已审核数量、已获得余额
		LambdaQueryWrapper<AuditRecord> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(AuditRecord::getUserId, userId);

		List<AuditRecord> auditRecords = auditRecordMapper.selectList(wrapper);
		BigDecimal obtainBalance = auditRecords.stream()
				.filter(auditRecord -> auditRecord.getStatusId() == 2) // 筛选状态为2的记录
				.map(auditRecord -> BigDecimal.valueOf(auditRecord.getAuditMoney()))
				.reduce(BigDecimal.ZERO, BigDecimal::add);
		long passCount = auditRecords.stream()
				.filter(auditRecord -> auditRecord.getStatusId() == 2)
				.count();
		long pendingCount = auditRecords.stream()
				.filter(auditRecord -> auditRecord.getStatusId() == 1)
				.count();
		userInfo.setObtainBalance(obtainBalance).setPassOrderCount(passCount).setPendingOrderCount(pendingCount);

		return userInfo;
	}

	@Override
	public Map<String, String> login(String loginCode, String token) {
		// 如果token存在且用户在数据库，则返回新的token
		if (StrUtil.isNotBlank(token)) {
			if (JwtUtil.verifyToken(token)) {
				// 解析id
				String userId = JwtUtil.parseTokenId(token);
				if (Long.parseLong(userId) > 10000) {
					throw new ServiceException("传入token不属于用户");
				}
				String newToken = JwtUtil.generateToken(userId);
				return Map.of("userId", userId, "token", newToken, "isFirstLogin", "false");
			}
		}
		// 检查loginCode
		if (StrUtil.isBlank(loginCode)) {
			throw new ServiceException("loginCode不能为空");
		}
		WechatReturnObjectDTO wechatReturnObj = wechatUtil.validLoginCodeFromWechat(loginCode);
		String openid = wechatReturnObj.getOpenid();

		LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(User::getOpenid, openid);
		User user = userMapper.selectOne(wrapper);
		HashMap<String, String> map = new HashMap<>();
		map.put("isFirstLogin", "false");
		if (ObjectUtil.isNull(user)) {
			LocalDateTime now = LocalDateTime.now();
			user = User.builder()
					.openid(wechatReturnObj.getOpenid())
					.nickname("游客" + RandomUtil.randomNumbers(6))
					.createTime(now)
					.modifyTime(now)
					.salt(RandomUtil.randomString(6))
					.build();
			userMapper.insert(user);
			map.put("isFirstLogin", "true");
		}
		token = JwtUtil.generateToken(user.getUserId().toString());

		map.put("merchantId", String.valueOf(user.getUserId()));
		map.put("token", token);
		return map;
	}
}




